package com.heima.kafka.sample;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-17 10:11
 */
public class ProducerQuickStart109 {

    public static void main(String[] args) {
        //创建配置对象
        Properties properties = new Properties();
        //kakfa地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //序列化方式 key value
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);

//        String abc = "123";
//        //转成二进制
//        byte[] bytes = abc.getBytes(StandardCharsets.UTF_8);
//        //二进制还原成对象
//        String s = new String(bytes,StandardCharsets.UTF_8);

        //创建生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        for (int i = 0; i < 10; i++) {
            //发送消息
            ProducerRecord<String, String> producerRecord =
                    new ProducerRecord<String, String>("stream109_source","hello kafka");


                //发送之后，消息未必到达kafka 同步调用
                Future<RecordMetadata> future = producer.send(producerRecord);

//                //执行额外的业务逻辑
//
//                //get方法会等待kafka结果返回
//                RecordMetadata recordMetadata = future.get();
//
//                System.out.println(Thread.currentThread().getName());
//
//
//                //异步调用，不用等结果返回，让另外一个线程等待，返回之后执行方法
//                producer.send(producerRecord, (recordMetadata1, e) -> {
//                    //打印信息
//                    System.out.println(Thread.currentThread().getName());
//                    System.out.println(recordMetadata1);
//                });


        }


        //关闭生产者
        producer.close();
    }
}
